package com.example.schoolhospitalsystem;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class AppointmentActivity extends AppCompatActivity {

    private Spinner spDepartment, spDoctor, spDate, spTime;
    private TextView tvSelectedDepartment, tvSelectedDoctor, tvSelectedDate, tvSelectedTime;
    private Button btnMakeAppointment;
    private String userId, userRole;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appointment);

        // 获取用户信息（从 Intent 传递，需确保调用方传入）
        Intent intent = getIntent();
        userId = intent.getStringExtra("userId");
        userRole = intent.getStringExtra("userRole");

        // 初始化视图
        spDepartment = findViewById(R.id.sp_department);
        spDoctor = findViewById(R.id.sp_doctor);
        spDate = findViewById(R.id.sp_date);
        spTime = findViewById(R.id.sp_time);
        tvSelectedDepartment = findViewById(R.id.tv_selected_department);
        tvSelectedDoctor = findViewById(R.id.tv_selected_doctor);
        tvSelectedDate = findViewById(R.id.tv_selected_date);
        tvSelectedTime = findViewById(R.id.tv_selected_time);
        btnMakeAppointment = findViewById(R.id.btn_make_appointment);

        // 初始化科室 Spinner
        initDepartmentSpinner();

        // 科室选择监听：加载对应医生
        spDepartment.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String department = (String) parent.getItemAtPosition(position);
                tvSelectedDepartment.setText("选择的科室: " + department);
                // 模拟从数据库加载医生
                List<String> doctors = getDoctorsByDepartment(department);
                updateSpinner(spDoctor, doctors);
                // 重置医生选择，避免残留旧数据
                tvSelectedDoctor.setText("选择的医生: ");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 医生选择监听：解析余号，禁用按钮（无号时）
        spDoctor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String doctorInfo = (String) parent.getItemAtPosition(position);
                tvSelectedDoctor.setText("选择的医生: " + doctorInfo);
                // 解析余号，校验是否可预约
                int remain = parseRemainNumber(doctorInfo);
                if (remain <= 0) {
                    btnMakeAppointment.setEnabled(false);
                    tvSelectedDoctor.setError("该医生无余号");
                } else {
                    btnMakeAppointment.setEnabled(true);
                    tvSelectedDoctor.setError(null);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 日期选择监听：加载对应时间段
        spDate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedDate = (String) parent.getItemAtPosition(position);
                tvSelectedDate.setText("选择的日期: " + selectedDate);
                // 根据医生和日期加载时间段
                String doctorInfo = tvSelectedDoctor.getText().toString().replace("选择的医生: ", "");
                initTimeSpinner(doctorInfo, selectedDate);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 时间段选择监听：校验余号
        spTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedTime = (String) parent.getItemAtPosition(position);
                tvSelectedTime.setText("选择的时间段: " + selectedTime);
                // 重新校验余号（防止选时间后余号变化）
                String doctorInfo = tvSelectedDoctor.getText().toString().replace("选择的医生: ", "");
                int remain = parseRemainNumber(doctorInfo);
                if (remain <= 0) {
                    btnMakeAppointment.setEnabled(false);
                    tvSelectedTime.setError("该时段无余号");
                } else {
                    btnMakeAppointment.setEnabled(true);
                    tvSelectedTime.setError(null);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 预约按钮点击事件
        btnMakeAppointment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String department = tvSelectedDepartment.getText().toString().replace("选择的科室: ", "");
                String doctorInfo = tvSelectedDoctor.getText().toString().replace("选择的医生: ", "");
                String date = tvSelectedDate.getText().toString().replace("选择的日期: ", "");
                String time = tvSelectedTime.getText().toString().replace("选择的时间段: ", "");

                // 校验是否选全
                if (department.isEmpty() || doctorInfo.isEmpty() || date.isEmpty() || time.isEmpty()) {
                    Toast.makeText(AppointmentActivity.this, "请选择完整的预约信息", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 执行预约（模拟扣减余号）
                if (makeAppointment(userId, doctorInfo, date, time)) {
                    Toast.makeText(AppointmentActivity.this, "预约成功", Toast.LENGTH_SHORT).show();
                    finish(); // 预约成功后关闭页面（可调整为跳转到预约列表）
                } else {
                    Toast.makeText(AppointmentActivity.this, "预约失败，该时段可能已被预约", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 初始化科室 Spinner
    private void initDepartmentSpinner() {
        List<String> departmentList = new ArrayList<>();
        departmentList.add("内科");
        departmentList.add("外科");
        departmentList.add("妇产科");
        departmentList.add("儿科");

        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                departmentList
        );
        spDepartment.setAdapter(adapter);
    }

    // 根据科室加载医生（模拟数据库查询）
    private List<String> getDoctorsByDepartment(String department) {
        List<String> doctors = new ArrayList<>();
        if ("内科".equals(department)) {
            doctors.add("张医生 - 主任医师 - 简介：擅长内科常见疾病治疗 - 余号：5");
            doctors.add("李医生 - 副主任医师 - 简介：有丰富内科经验 - 余号：3");
        } else if ("外科".equals(department)) {
            doctors.add("王医生 - 主治医师 - 简介：专注外科手术 - 余号：4");
            doctors.add("赵医生 - 住院医师 - 简介：积极参与外科诊疗 - 余号：2");
        } else if ("妇产科".equals(department)) {
            doctors.add("陈医生 - 主任医师 - 简介：擅长妇产科疾病 - 余号：6");
        } else if ("儿科".equals(department)) {
            doctors.add("孙医生 - 主治医师 - 简介：专注儿科诊疗 - 余号：4");
        }
        return doctors;
    }

    // 初始化日期 Spinner
    private void initDateSpinner() {
        List<String> dateList = new ArrayList<>();
        dateList.add("2025-07-02");
        dateList.add("2025-07-03");
        dateList.add("2025-07-04");
        dateList.add("2025-07-05");
        dateList.add("2025-07-06");
        dateList.add("2025-07-07");
        dateList.add("2025-07-08");

        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                dateList
        );
        spDate.setAdapter(adapter);
    }

    // 根据医生和日期加载时间段（模拟数据库查询）
    private void initTimeSpinner(String doctorInfo, String selectedDate) {
        List<String> timeList = new ArrayList<>();
        // 实际应根据医生、日期查询可预约时段，这里直接模拟
        timeList.add("08:00-08:30");
        timeList.add("08:30-09:00");
        timeList.add("09:00-09:30");
        timeList.add("09:30-10:00");
        timeList.add("10:00-10:30");
        timeList.add("10:30-11:00");
        timeList.add("13:30-14:00");
        timeList.add("14:00-14:30");
        timeList.add("14:30-15:00");
        timeList.add("15:00-15:30");
        timeList.add("15:30-16:00");
        timeList.add("16:00-16:30");

        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                timeList
        );
        spTime.setAdapter(adapter);
    }

    // 更新 Spinner 数据的工具方法
    private void updateSpinner(Spinner spinner, List<String> data) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                data
        );
        spinner.setAdapter(adapter);
    }

    // 解析医生信息中的余号
    private int parseRemainNumber(String doctorInfo) {
        int index = doctorInfo.lastIndexOf("余号：");
        if (index != -1) {
            String numStr = doctorInfo.substring(index + 4).trim();
            if (!numStr.isEmpty()) { // 校验非空
                return Integer.parseInt(numStr);
            }
        }
        return 0; // 解析失败时返回默认值（如 0）
    }

    // 模拟预约操作（扣减余号，实际应调用数据库）
    private boolean makeAppointment(String patientId, String doctorInfo, String date, String time) {
        // 1. 解析当前余号
        int remain = parseRemainNumber(doctorInfo);
        if (remain <= 0) {
            return false;
        }
        // 2. 扣减余号（模拟）
        String newDoctorInfo = doctorInfo.replace("余号：" + remain, "余号：" + (remain - 1));
        // 3. 更新医生 Spinner 显示（可选，实际应更新数据库后重新查询）
        String department = tvSelectedDepartment.getText().toString().replace("选择的科室: ", "");

        // 补充返回值：预约逻辑走完且未提前 return false 时，返回 true
        return true;
    }
}